package com.example.customer.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ApiExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(value = ApiException.class)
    public ResponseEntity<ExceptionResponse> handleApiException(ApiException e) {
        log.warn("业务异常: {}", e.getMessage());

        ExceptionResponse exception = ExceptionResponse.builder()
                .message(e.getMessage())
                .code(HttpStatus.BAD_REQUEST.value())
                .timestamp(System.currentTimeMillis())
                .build();

        return new ResponseEntity<>(exception, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理参数绑定异常（校验失败）
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<ExceptionResponse> handleBindError(BindException e) {
        log.warn("参数绑定异常", e);

        FieldError error = e.getFieldError();
        String message = String.format("字段[%s]校验失败: %s",
                error != null ? error.getField() : "未知字段",
                error != null ? error.getDefaultMessage() : "未知错误");

        ExceptionResponse exception = ExceptionResponse.builder()
                .message(message)
                .code(HttpStatus.BAD_REQUEST.value())
                .timestamp(System.currentTimeMillis())
                .build();

        return new ResponseEntity<>(exception, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExceptionResponse> handleGenericException(Exception e) {
        log.error("系统异常", e);

        ExceptionResponse exception = ExceptionResponse.builder()
                .message("系统内部错误，请稍后重试")
                .code(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .timestamp(System.currentTimeMillis())
                .build();

        return new ResponseEntity<>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}